package com.hopu.springbootdemo2.controller;

import com.hopu.springbootdemo2.entity.PageEntity;
import com.hopu.springbootdemo2.entity.User;
import com.hopu.springbootdemo2.entity.UserVO;
import com.hopu.springbootdemo2.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;

@CrossOrigin //解决跨域问题
@RestController //定义控制器
public class UserController {

    //调用service
    @Resource
    private UserService userService;

    /**
     * 方式1 ：传统servlet，通过请求对象获得参数
     */
//    @RequestMapping("/login")
//    public ResponseEntity<User> login(HttpServletRequest req){
//        String userName = req.getParameter("username");
//        String userPwd = req.getParameter("password");
//        User user = userService.login(userName, userPwd);
//        //将登录验证结果发送前端 ---> JSON ---> jackson
//        return ResponseEntity.ok(user);
//    }

//    /**
//     * 方式2 ： 直接定义参数
//     */
//    @PostMapping("/user/login")
//    public ResponseEntity<UserVO> login(String username, String password){
//        UserVO user = userService.login(username, password);
//        return ResponseEntity.ok(user);
//    }

    @GetMapping("/user/page")
    public ResponseEntity<PageEntity<User>> page(
            @RequestParam(required = false,defaultValue = "1") Integer current,
            @RequestParam(required = false,defaultValue = "10")  Integer pageSize) {
        //查询用户
        PageEntity<User> users = userService.findUserPage(current,pageSize);
        //转换为JSON,通过流发送给客户端
        return ResponseEntity.ok(users);
    }

    /**
     * 方式3：通过对象传参
     */
    @PostMapping("/user")
    public ResponseEntity<Boolean> save(@RequestBody User user) {
        //查询用户
        userService.save(user);
        return ResponseEntity.ok(true);
    }

    @PutMapping("/user")
    public ResponseEntity<Boolean> update(@RequestBody User user){
        //查询用户
        userService.update(user);
        return ResponseEntity.ok(true);
    }

    @DeleteMapping("/user/{user_id}")
    public ResponseEntity<Boolean> delete(@PathVariable("user_id") String user_id) {
        //查询用户
        boolean rs = userService.remove(user_id);
        return ResponseEntity.ok(rs);
    }
}
